<template>
  <div class="page-controller">
    <FISearchForm
      v-show="showSearch"
      class="box-radius2"
      ref="ruleFormRef"
      :id="`inqu_${tableId}`"
      :searchFormId="tableId"
      :search-table-id="tableId"
      :searchNum="searchItemCount"
      :model="state.query"
      v-model:form-value="state.query"
      :table-column="columns"
      :wrapperSpan="searchWrapperSpan"
      :showCollapse="false"
      :showDynamicForm="true"
      @submit="searchFn"
      @deleteFilterItem="deleteFilterItem"
    >
      <el-col :span="searchWrapperSpan" class="flex-center">
        <FIFormItem prop="fkey" label="配置代码">
          <FIInput v-model="state.query.fkey" clearable />
        </FIFormItem>
      </el-col>
      <el-col :span="searchWrapperSpan" class="flex-center">
        <FIFormItem name="configEnvId" label="配置环境">
          <FISelect
            v-if="arr2.length > 0"
            v-model="state.query.configEnvId"
            valueCustom="value"
            :options="arr2"
            clearable
          />
        </FIFormItem>
      </el-col>
    </FISearchForm>
    <div class="margin-bottom20"></div>
    <!-- @handleSelectionChange="handleSelectionChange" -->
    <FITable
      class="box-radius2"
      :id="`inqu_${tableId}`"
      :tableId="tableId"
      :readonly="false"
      :data="state.dataList"
      v-model:columns="columns"
      :toolbarConfig="true"
      :isCanAddRow="true"
      :locked="isTableLocked"
      :isLoading="isTableLoading"
      checkMode="check"
      insertable
      delete-id="deleteSeqDef"
      deletable
      :saveSuccessful="saveSuccessful"
      :pageConfig="pageConfig"
      @row-add-save="addRowSave"
      @filter-reset="searchFn"
      @column-filter-confirm="filterConfirm"
      @change-sort="searchFn"
      @table-refresh="searchFn"
      @lock-toggle="isTableLocked = !isTableLocked"
      @search-toggle="showSearch = !showSearch"
      @selection-change="handleSelectionChange"
      @size-change="handleSizeChange"
      @current-page-change="handleCurrentChange"
      @row-delete="deleteRow"
    >
      <template #configEnvId="{ scope }">
        <FISelect
          v-if="scope.row.isSelected"
          v-model="scope.row.configEnvId"
          valueCustom="value"
          :options="arr2"
          clearable
        />
        <span v-else>{{ configEnvIdFucn(scope.row.configEnvId, scope.$index) }}</span>
      </template>

      <!-- <template #headerBtn>
        <FIPopconfirmBtn
          title="您是否确认要生删除选中数据吗？"
          buttonText="删除"
          :btn-binds="{ id: 'deleteSeqDef', border: true }"
          @confirm="deleteRow"
        >
        </FIPopconfirmBtn>
      </template> -->
      <template #empty> 暂无数据 </template>
    </FITable>
  </div>
</template>
<script lang="ts" setup>
import { reactive, onMounted, ref, computed, watch } from 'vue'
import FISearchForm from '@/components/FISearchForm.vue'
import FIFormItem from '@/components/FIFormItem.vue'
import FIInput from '@/components/FIInput.vue'
import FIPopconfirmBtn from '@/components/FIPopconfirmBtn.vue'
import FITable from '@/components/FITable/index.vue'
// import OyTable from '@/components/OyTable/index.vue'
import FISelect from '@/components/FISelect/index.vue'
import { apiRequestPost } from '@/api/globalApi.js'
import LocalCache from '@/utils/cache'
import { clientFilter } from '@/utils/common.js'
import { ElMessage } from 'element-plus'
import { useMessage } from '@/hooks/message'
import type { PageConfig, Column } from '@/types/components'
import { apiGetenv } from '@/api/configEnvMaint/index.ts'
import { useRoute } from 'vue-router'
import { getCurrentInstance } from 'vue'
const { proxy } = getCurrentInstance() // 获取当前组件实例上下文
const route = useRoute()
const searchWrapperSpan = 8
const showSearch = ref(true)
const isTableLocked = ref(false)
const isTableLoading = ref(false)
// 页面编码
const tableId = 'configInfoMaint'
// 保存成功按钮状态，默认不展示底部保存，取消按钮
const saveSuccessful = ref(false)
const state = reactive({
  query: {
    fkey: '',
    configEnvId: '',
    dynamicParams: [],
    orderbyParams: [],
    current: 1,
    size: 10,
  },
  dataList: [],
})
const pageConfig: PageConfig = reactive({
  total: 0,
  currentPage: 1,
})

const columns: Column = reactive([
  {
    label: '配置环境',
    prop: 'configEnvId',
    align: 'center',
    queryName: '',
    editable: true,
    // sortable: true,
    // filterable: true,
    readonly: true,
    modelValue: { inputValue: '' },
    editType: 'input',
    editConfig: {
      rules: { configEnvId: [{ required: true }] },
    },
  },
  {
    label: '配置代码',
    prop: 'fkey',
    queryName: 'tedfa00.form_Cname',
    align: 'center',
    editType: 'input',
    editable: true,
    // readonly:true,
    // filterable: true,
    // sortable: true,
    sortValue: '',
    modelValue: { inputValue: '' },
    editConfig: {
      rules: { fkev: [{ required: true, message: '请输入配置值内容', trigger: 'blur' }] },
    },
  },

  // {
  //   label: '配置项类别',
  //   prop: 'configType',
  //   align: 'center',
  //   width: '180',
  //   queryName: '',
  //   editable: true,
  //   sortable: true,
  //   filterable: true,
  //   modelValue: { inputValue: '' },
  //   editType: 'input',
  //   editConfig: {
  //     rules: { configType: [{ required: false, message: '请输入配置项类别', trigger: 'blur' }] },
  //   },
  // },
  {
    label: '配置状态',
    prop: 'status',
    align: 'center',
    editable: true,
    // filterable: true,
    // sortable: true,
    editType: 'select',
    modelValue: [],
    configValueToLable: {
      list: [
        { value: 1, label: '是' },
        { value: 0, label: '否' },
      ],
    },
    editConfig: {
      rules: { status: [{ required: true, message: '请输入是否连号', trigger: 'blur' }] },
      options: [
        { value: 1, label: '是' },
        { value: 0, label: '否' },
      ],

      selectBinds: {
        multiple: false,
        valueCustom: 'value',
      },
    },
  },

  {
    label: '配置项提示',
    prop: 'configCue',
    align: 'center',
    editable: true,
    modelValue: { inputValue: '' },
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },

  {
    label: '配置项类别',
    prop: 'configType',
    align: 'center',
    editable: true,
    // filterable: true,
    // sortable: true,
    editType: 'select',
    modelValue: [],
    configValueToLable: {
      list: [
        { value: '1', label: '平台设置' },
        { value: '2', label: '项目配置' },
      ],
    },
    editConfig: {
      rules: { configType: [{ required: true, message: '请输入配置', trigger: 'blur' }] },
      options: [
        { value: '1', label: '平台设置' },
        { value: '2', label: '项目配置' },
      ],
      // codeOption:{ codesetCode:'city'},
      selectBinds: {
        multiple: false,
        valueCustom: 'value',
      },
    },
  },
  {
    label: '配置项描述',
    prop: 'configDesc',
    editable: true,
    align: 'center',
    modelValue: { inputValue: '' },
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },

  {
    label: '配置值内容',
    prop: 'fvalue',
    queryName: 'tedfa00.form_Cname',
    align: 'center',
    editType: 'input',
    editable: true,
    // filterable: true,
    // sortable: true,
    sortValue: '',
    modelValue: { inputValue: '' },
    editConfig: {
      rules: { fvalue: [{ required: true, message: '请输入配置值内容', trigger: 'blur' }] },
    },
  },
  {
    label: '创建人',
    prop: 'recCreator',
    align: 'center',
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  {
    label: '创建时间',
    prop: 'recCreateTime',
    align: 'center',
    editType: 'time-picker', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  {
    label: '修改人',
    prop: 'recRevisor',
    align: 'center',
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  {
    label: '修改时间',
    prop: 'recReviseTime',
    align: 'center',
    editType: 'date-picker', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
])
// 列自定义筛选事件
const filterConfirm = (e: any) => {
  let selectedProp = e.columnItem.prop
  Array.isArray(columns) &&
    columns.forEach((item: any) => {
      if (item?.prop == selectedProp) {
        item.modelValue = e.columnItem?.modelValue
        item.showHighSearch = true
      }
    })
  searchFn('dynamic')
}
const configEnvIdFucn = (id, index) => {
  for (let i of arr2.value) {
    if (i.value == id) {
      return i.label
    }
  }
  // arr2.value.forEach((item: any) =>{
  //   if(item.value == id){
  //     console.log(item.label,'item.label')
  //     return item.label
  //   }
  // })
}
const deleteFilterItem = (e: any) => {
  let selectedProp = e
  Array.isArray(columns) &&
    columns.forEach((item: any) => {
      if (item?.prop == selectedProp) {
        item.modelValue = null
        item.showHighSearch = false
      }
    })
  searchFn()
}
const checkedRows = ref([])
const handleSelectionChange = (e) => {
  checkedRows.value = e
}

// 常规搜索条件个数
const searchItemCount = computed(() => {
  let filledCount = 0
  const outKeys = ['dynamicParams', 'orderbyParams', 'size', 'current']
  // 下面是从第三项起计算常规搜索条件有值个树
  // 获取state.query的所有keys
  const queryKeys = Object.keys(state.query).filter((key) => !outKeys.includes(key))
  if (queryKeys.length < 3) return 0
  // 从第三项开始计算
  queryKeys.slice(2).forEach((key) => {
    if (state.query[key] !== '' && state.query[key] !== null) {
      filledCount++
    }
  })
  return filledCount
})
const searchFn = (type?: string, columnsVal?: any) => {
  if (type == 'sort') {
    if (columns.length === columnsVal.length) {
      for (let i = 0; i < columns.length; i++) {
        columns[i].sortValue = columnsVal[i].sortValue
      }
    }
  }
  // 缓存筛选条件 --筛选条件包括常规筛选内容，还有动态的筛选内容 dynamicParams，排序orderbyParams等等内容
  const userData = LocalCache.getCache('user')
  const userId = userData.userId
  LocalCache.setCache(`${userId}-${tableId}-searchFormId`, state.query)
  // table锁定时客户端筛选 queryData根据具体页面数据赋值
  if (isTableLocked.value && type === 'dynamic') {
    state.dataList = clientFilter(state.query, state.dataList)
  } else {
    state.query.dynamicParams = []
    state.query.orderbyParams = []
    Array.isArray(columns) &&
      columns.forEach((item: any) => {
        // 排序
        if (item.sortable && item.sortValue) {
          const orderObj = {
            name: item.prop,
            queryName: item.queryName || item.prop,
            ops: item.sortValue,
          }
          state.query.orderbyParams.push(orderObj)
        }
        // 筛选
        if (item.showHighSearch === true) {
          if (item.editType === 'input') {
            const dynamicItem = {
              name: item.prop,
              queryName: 'tedfa00.form_Cname',
              ops: 'like',
              val: [item.modelValue?.inputValue || ''],
            }
            // 空
            if (item.modelValue?.isBlank) {
              dynamicItem.ops = 'isBlank'
              state.query.dynamicParams.push(dynamicItem)
            }
            // 非空
            if (item.modelValue?.notBlank) {
              dynamicItem.ops = 'notBlank'
              state.query.dynamicParams.push(dynamicItem)
            }

            if (!item.modelValue?.notBlank && !item.modelValue?.isBlank && item.modelValue?.inputValue) {
              state.query.dynamicParams.push(dynamicItem)
            }
          }
        }
      })
    isTableLoading.value = true
    if(type == 'page'){
      state.query.current = pageConfig.currentPage
    }else{
      pageConfig.currentPage = 1
      state.query.current = 1
    }
    if (pageConfig.pageSize) state.query.size = pageConfig.pageSize
    apiRequestPost('/rm2/configInfoMaint/query', state.query)
      .then((res) => {
        isTableLoading.value = false
        if (res.data.success) {
          state.dataList = res.data.data.result
          pageConfig.pageSize = Number(res.data.data.size)
          pageConfig.total = Number(res.data.data.count)
        } else {
          ElMessage.error(res.data.message)
        }
      })
      .catch((error: any) => {
        isTableLoading.value = false
        // 处理错误
      })
  }
}
const handleModify = (obj, type = 'modify') => {
  const changeList = type === 'add' ? obj : [obj.action]
  isTableLoading.value = true
  saveSuccessful.value = false
  apiRequestPost('/rm2/configInfoMaint/save', changeList)
    .then((res) => {
      isTableLoading.value = false
      // state.dataList = res.data.data.result
      if (res.data.success) {
        useMessage().success(res.data.message)
        saveSuccessful.value = true
        searchFn()
      } else {
        ElMessage.error(res.data.message)
      }
    })
    .catch((error: any) => {
      isTableLoading.value = false
      // 处理错误
    })
}
const deleteRow = () => {
  console.log(checkedRows.value, '00000')
  if (!checkedRows.value.length) {
    useMessage().warning('请选择一条数据')
    return
  }
  let ids = []
  Array.isArray(checkedRows.value) &&
    checkedRows.value.forEach((item: any) => {
      if (item?.configEnvId) {
        let val = `${item.configEnvId}-${item.fkey}`
        ids.push(val)
      }
    })
  isTableLoading.value = true
  const apiUrl = proxy.$Button_api('deleteSeqDef', route.name)
  apiRequestPost(apiUrl, ids)
    .then((res) => {
      isTableLoading.value = false
      searchFn()
    })
    .catch((error: any) => {
      isTableLoading.value = false
    })
}
const ruleFormRef = ref(null)

const addRowSave = (data) => {
  handleModify(data, 'add')
}
const handleSizeChange = (e) => {
  pageConfig.pageSize = e
  pageConfig.currentPage = 1
  searchFn()
}
const handleCurrentChange = (e) => {
  pageConfig.currentPage = e
  searchFn('page')
}
const arr2 = ref([])
const getProjectenv = () => {
  let data = {
    size: 999,
  }
  apiGetenv(data).then((res) => {
    if (res.data.success) {
      Array.isArray(res.data.data.result) &&
        res.data.data.result.forEach((item) => {
          // item.label = item.moduleCname2
          item.label = item.configEnvCname
          item.value = item.configEnvId
        })

      if (Array.isArray(res.data.data.result)) {
        const newArray = res.data.data.result.map((item) => ({
          label: item.configEnvCname,
          value: item.configEnvId,
        }))
        // columns[3].editConfig.options = newArray
        // columns.editConfig.options = newArray
        // 在 DOM 更新后执行的操作
        arr2.value = newArray
      }
      console.log(arr2, 'arr2123')
    }
  })
  // 如果是下拉框字段，触发接口获取选项
  //  this.fetchOptions(row旧值); // 根据旧值或上下文决定如何查询
}
onMounted(() => {
  getProjectenv()
  // 获取查询条件缓存
  const userData = LocalCache.getCache('user')
  const userId = userData.userId
  state.query = LocalCache.getCache(`${userId}-${tableId}-searchFormId`)
    ? LocalCache.getCache(`userId-${tableId}-searchFormId`)
    : state.query
  searchFn()
})
</script>
<style lang="less" scoped></style>
